package host.skiree.nettydemo.client.handler;

import host.skiree.nettydemo.message.RpcResponseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author gcl
 * @date 2022/9/27 9:18
 */
public class DemoRpcClientHandler extends SimpleChannelInboundHandler<RpcResponseMessage> {

    /**
     * 用来接收结果的集合
     * 不能使用通配符，如果使用通配符，不能放只能取，(除了放null)
     * https://blog.csdn.net/Trustme0594184/article/details/80146865
     */
    public static final Map<Integer, Promise<Object>> PROMISES_MAP = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, RpcResponseMessage msg) throws Exception {
        // 此处使用remove, 使用一次后就用不到了，及时清理
        Promise<Object> promise = PROMISES_MAP.remove(msg.getSequenceId());
        if (!Objects.isNull(promise)){
            if ( Objects.isNull(msg.getExceptionValue()) ){
                // 调用成功设置结果
                promise.setSuccess(msg.getReturnValue());
            }else {
                // 调用失败设置结果
                promise.setFailure(msg.getExceptionValue());
            }
        }
    }
}
